package com.example.cargroup.viewmodel;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.cargroup.adapter.ConfirmOrderAdapter;
import com.example.cargroup.data.entity.Order;
import com.example.cargroup.data.entity.OrderEntity;
import com.example.cargroup.data.entity.OrderGoods;
import com.example.cargroup.data.entity.PayEntity;
import com.example.cargroup.data.entity.ShipAddress;
import com.example.cargroup.model.OrderModel;
import com.example.mvvmcommon.arouterprovider.UserProvider;
import com.example.mvvmcommon.field.UIField;
import com.example.mvvmcommon.mvvm.viewmodel.BaseViewModel;
import com.example.networkmoudel.entity.BaseEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ConfirmOrderViewModel extends BaseViewModel<OrderModel> implements View.OnClickListener, OnItemClickListener {

    public ObservableField<String> totalPrice = new ObservableField<>("合计: 0");
    public ConfirmOrderAdapter adapter = new ConfirmOrderAdapter();
    public ObservableField<String>shipname = new ObservableField<>("");
    public ObservableField<String>shipaddress = new ObservableField<>("");
    public ObservableField<Boolean>shipflag = new ObservableField<>(false);
    private List<OrderGoods> list;
    public int ordernum = 0;
    private float price = 0f;
    ShipAddress shipAddressEntity = new ShipAddress();

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        adapter.setOnItemClickListener(this);
        Map<String,Object> map = new HashMap<>();
        map.put("orderId",ordernum);
        m.requestGetOrder(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    @Override
    protected OrderModel createModel() {
        return new OrderModel();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void payResult(String result){
        //验证订单是否支付成功
        Map<String,Object>map = new HashMap<>();
        map.put("orderId",ordernum);
        m.requestOrderPay(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    @Override
    protected void sucessFull(BaseEntity entity) {
        if (entity instanceof OrderEntity){
            OrderEntity orderEntity = (OrderEntity) entity;
            int id = ((UserProvider) ARouter.getInstance().build("/usergroup/userprovider").navigation()).getUserId();
            ShipAddress shipAddress1 = orderEntity.data.shipAddress;
            if (shipAddress1==null){
                showMsg("地址为空");
                return;
            }
            shipAddressEntity.id = id;
            shipAddressEntity.ship_user_name = shipAddress1.ship_user_name;
            shipAddressEntity.ship_user_mobile = shipAddress1.ship_user_mobile;
            shipAddressEntity.ship_address = shipAddress1.ship_address;
            shipAddressEntity.ship_is_default = shipAddress1.ship_is_default;
            shipAddressEntity.user_id = id;
            list = orderEntity.data.orderGoodsList;
            if (list == null)
                return;
            if (list.size() == 0)
                return;
            price = 0f;
            for (OrderGoods goods : list){
                price+=(Float.valueOf(goods.goods_price)*goods.goods_count);
            }
            totalPrice.set("合计: "+price);
            adapter.setNewInstance(list);
        }else if (entity instanceof PayEntity){
            PayEntity payEntity = (PayEntity) entity;
            //支付宝信息返回
            String alipayStr = payEntity.data;
            Map<String,Object>map=new HashMap<>();
            map.put(UIField.ACTIONTYPE,UIField.AROUTERSTART);
            map.put(UIField.ACTIONROUTERKEY,"/app/alipayactivity");
            Bundle bundle = new Bundle();
            bundle.putString("alipayStr",alipayStr);
            map.put(UIField.VALUESKEY,bundle);
            getUiChangeLiveData().getStartActivity().setValue(map);
        }else {
            if (entity.getMessage().equals("订单提交成功")){
                //订单状态修改为等待支付
                Map<String ,Object>map = new HashMap<>();
                map.put("orderId",ordernum);
                map.put("totalPrice",price);
                m.requestPaySign(map).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(this);
            }else if (entity.getMessage().equals("订单支付成功")){
               showMsg("订单支付成功");
               finish();
            }
        }
    }

    public void subOrderListener(){
        if (list==null){
            showMsg("没有任何待支付商品");
            return;
        }
        if (list.size()==0){
            showMsg("没有任何待支付商品");
            return;
        }
        int id = ((UserProvider) ARouter.getInstance().build("/usergroup/userprovider").navigation()).getUserId();
        if (id == 0){
            //跳转到登录界面
            Map<String,Object>pageMap = new HashMap<>();
            pageMap.put(UIField.ACTIONTYPE,UIField.AROUTERSTART);
            pageMap.put(UIField.ACTIONROUTERKEY,"/user/login");
            getUiChangeLiveData().getStartActivity().setValue(pageMap);
        }
        //计算总金额
        price=0f;
        for (OrderGoods goods : list){
            price+=(Float.valueOf(goods.goods_price)*goods.goods_count);
        }
        Map<String,Object>map = new HashMap<>();
        map.put("userId",id);


        Order orderEntity = new Order();
        orderEntity.id = ordernum;
        orderEntity.totalPrice = ""+price;
        orderEntity.payType = 0;
        orderEntity.orderStatus = 0;
        orderEntity.orderGoodsList = list;
        orderEntity.shipAddress = shipAddressEntity;
        map.put("order",orderEntity);
        m.requestSubOrder(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    public void finish(){
        getUiChangeLiveData().getFinishActivity().setValue(""+System.currentTimeMillis());
    }

    @Override
    public void onClick(View v) {
        Map<String,Object>pageMap = new HashMap<>();
        pageMap.put(UIField.ACTIONTYPE,UIField.AROUTERSTART);
        pageMap.put(UIField.ACTIONROUTERKEY,"/cargroup/shipaddressactivity");
        getUiChangeLiveData().getStartActivity().setValue(pageMap);
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        //跳转商品页面
        ConfirmOrderAdapter confirmOrderAdapter= (ConfirmOrderAdapter) adapter;
        Bundle bundle = new Bundle();
        bundle.putString("img", confirmOrderAdapter.getItem(position).goods_icon);
        bundle.putString("title", confirmOrderAdapter.getItem(position).goods_desc);
        bundle.putString("dec", confirmOrderAdapter.getItem(position).goods_sku);
        bundle.putInt("id", confirmOrderAdapter.getItem(position).goods_id);
        bundle.putString("price", confirmOrderAdapter.getItem(position).goods_price);
        Map<String,Object>pageMap = new HashMap<>();
        pageMap.put(UIField.ACTIONTYPE,UIField.AROUTERSTART);
        pageMap.put(UIField.ACTIONROUTERKEY,"/homegroup/homevalueactivity");
        getUiChangeLiveData().getStartActivity().setValue(pageMap);

    }
}
